#region using

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using Sitecore.Data.Items;

#endregion

namespace Pentia.Linq
{
  internal class SitecoreQueryProvider : IQueryProvider
  {
    private readonly IQueryContext _contextData;

    public SitecoreQueryProvider(IQueryContext contextData)
    {
      _contextData = contextData;
    }

    public IQueryContext ContextData
    {
      get { return _contextData; }
    }

    public TextWriter Log { get; set; }

    #region IQueryProvider Members

    public IQueryable CreateQuery(Expression expression)
    {
      //TODO: Implement OfType operator support here
      throw new NotImplementedException();
    }

    public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
    {
      if (expression == null)
        throw new ArgumentNullException("expression");
      return new SitecoreQuery<TElement>(ContextData, expression) {Log = Log};
    }

    public object Execute(Expression expression)
    {
      throw new NotImplementedException();
    }

    public TResult Execute<TResult>(Expression expression)
    {
      if (expression == null)
        throw new ArgumentNullException("expression");

      IQueryable<TResult> query = CreateQuery<TResult>(expression);
      IEnumerator<TResult> result = query.GetEnumerator();
      return !result.MoveNext() ? default(TResult) : result.Current;
    }

    #endregion
  }
}